import subprocess
import datetime
import os
import re

def get_git_username():
    """从全局Git配置中获取用户名。"""
    try:
        result = subprocess.run(
            ['git', 'config', '--global', 'user.name'],
            capture_output=True,
            text=True,
            check=True
        )
        return result.stdout.strip()
    except subprocess.CalledProcessError:
        print("错误：无法获取Git用户名。请确保已使用 'git config --global user.name' 配置。")
        return None

def find_git_repos(base_dir):
    """在指定目录中递归查找所有Git仓库。"""
    repo_list = []
    for root, dirs, files in os.walk(base_dir):
        if '.git' in dirs:
            repo_list.append(root)
            # 找到Git仓库后，跳过其子目录的进一步扫描
            dirs.clear()
    return repo_list

def parse_git_stat(log_output):
    """
    解析 git log --stat 的输出，返回文件类型和修改行数的统计。
    """
    lines = log_output.strip().split('\n')
    stats = {
        "commits": 0,
        "total_insertions": 0,
        "total_deletions": 0,
        "file_type_stats": {}
    }
    
    commit_summary_pattern = re.compile(r'^(\d+) files? changed(, (\d+) insertions?)?(, (\d+) deletions?)?')
    file_stat_pattern = re.compile(r'(.+)\s+\|\s+.*')

    for line in lines:
        line = line.strip()
        
        if not line:
            continue
        
        # 匹配提交行
        if line.startswith('commit '):
            stats['commits'] += 1
            continue

        # 匹配文件统计摘要行 (e.g., '1 file changed, 2 insertions(+), 1 deletion(-)')
        summary_match = commit_summary_pattern.search(line)
        if summary_match:
            insertions = 0
            if summary_match.group(3):
                insertions = int(summary_match.group(3))
            
            deletions = 0
            if summary_match.group(5):
                deletions = int(summary_match.group(5))

            stats['total_insertions'] += insertions
            stats['total_deletions'] += deletions
            continue
        
        # 匹配单个文件的统计行 (e.g., 'components/KEY/keypower.c | 5 +--')
        file_match = file_stat_pattern.match(line)
        if file_match:
            file_path = file_match.group(1).strip()
            # 过滤不需要的目录
            if file_path.startswith('build/') or file_path.startswith('.history/'):
                continue
            
            _, file_extension = os.path.splitext(file_path)
            if file_extension:
                file_extension = file_extension.lower()
                stats['file_type_stats'].setdefault(file_extension, {"insertions": 0, "deletions": 0})
            
            # 统计 + 和 - 字符
            plus_count = line.count('+')
            minus_count = line.count('-')
            
            if file_extension:
                stats['file_type_stats'][file_extension]['insertions'] += plus_count
                stats['file_type_stats'][file_extension]['deletions'] += minus_count
                
    return stats


def get_today_logs(repo_path, username):
    """
    从单个仓库中检索指定用户今天的Git日志，并返回日志文本和统计数据。
    """
    today = datetime.date.today().strftime('%Y-%m-%d')
    
    # 构造Git日志命令，包括 --stat 选项
    command = [
        'git',
        'log',
        f'--author={username}',
        f'--since={today} 00:00:00',
        '--stat',
        '--date=short'
    ]
    try:
        result = subprocess.run(
            command,
            cwd=repo_path,
            capture_output=True,
            text=True,
            check=True,
            encoding='utf-8'
        )
        return result.stdout, parse_git_stat(result.stdout)
    except subprocess.CalledProcessError as e:
        # 如果不是有效的Git仓库，则不显示错误
        if "not a git repository" not in str(e.stderr):
            print(f"在仓库 '{repo_path}' 中运行Git命令时出错: {e.stderr.strip()}")
        return "", None
    except FileNotFoundError:
        print("错误：未找到Git可执行文件。请确保Git已安装并添加到系统PATH中。")
        return "", None

def main():
    """主函数，用于协调整个过程。"""
    username = get_git_username()
    if not username:
        return

    # 设置要扫描的根目录，请替换为你的实际路径。
    base_dir = r"C:" 

    today_date_str = datetime.date.today().strftime('%Y-%m-%d')
    output_file = f"git_logs_{today_date_str}.txt"
    
    all_logs = []
    total_stats = {
        "commits": 0,
        "total_insertions": 0,
        "total_deletions": 0,
        "file_type_stats": {}
    }

    print(f"正在扫描目录 '{base_dir}'，查找作者为 '{username}' 的今天提交记录。")
    
    repos = find_git_repos(base_dir)
    if not repos:
        print("未找到Git仓库。")
        return

    for repo_path in repos:
        print(f"  - 找到仓库: {repo_path}")
        logs, stats = get_today_logs(repo_path, username)
        if not logs or not stats:
            continue
        if logs and stats:
            all_logs.append(f"--- 仓库: {repo_path} ---\n{logs}")
            total_stats["commits"] += stats["commits"]
            total_stats["total_insertions"] += stats["total_insertions"]
            total_stats["total_deletions"] += stats["total_deletions"]
            for ext, s in stats["file_type_stats"].items():
                total_stats["file_type_stats"].setdefault(ext, {"insertions": 0, "deletions": 0})
                total_stats["file_type_stats"][ext]["insertions"] += s["insertions"]
                total_stats["file_type_stats"][ext]["deletions"] += s["deletions"]

    with open(output_file, "w", encoding="utf-8") as f:
        # 仅当文件为空时写入标题
        if os.path.getsize(output_file) == 0:
            f.write(f"每日Git提交日志（{today_date_str}）:\n\n")
        
        if all_logs:
            # 写入总览统计信息
            f.write("\n\n" + "="*50 + "\n")
            f.write(f"今日总览 ({today_date_str})\n")
            f.write("="*50 + "\n")
            f.write(f"总提交次数: {total_stats['commits']}\n")
            f.write(f"总修改行数: +{total_stats['total_insertions']} / -{total_stats['total_deletions']}\n\n")
            
            f.write("文件类型统计:\n")
            if total_stats['file_type_stats']:
                sorted_extensions = sorted(total_stats['file_type_stats'].items(), key=lambda item: item[1]['insertions'] + item[1]['deletions'], reverse=True)
                for ext, s in sorted_extensions:
                    f.write(f"  - {ext}: +{s['insertions']} / -{s['deletions']}\n")
            else:
                f.write("  - 无文件修改记录\n")
            
            f.write("\n" + "="*50 + "\n\n")
            
            f.write("\n".join(all_logs))
            print(f"\n成功！今天的Git日志已追加到 '{output_file}'。")
        else:
            print("\n今天未找到任何Git提交记录。")
            f.write(f"今天未找到任何Git提交记录。")

if __name__ == "__main__":
    main()
